<?php
namespace Swoole\Registry;
use Swoole\Socket\SocketClient;
use Swoole\Socket\IClient;
use Swoole\Socket\Timer;
use Common\FileUtil;
use Common\Log;
/**
 * Thrift 服务器端注册工具
 * 定时把当前thrift server状态更新到注册中心，接收注册中心其它thrift server地址信息
 */
class ThriftServerRegistry implements IClient{
    const THRIFT_SERVER = 1;
    const THRIFT_CLIENT = 2;
    private $config;
    private $client;
    private $host;
    private $port;
    private static $thriftServer = array();
    private static $regisrtyServer = array();
    function __construct($config){
        $this->config = $config;
        $this->initRegistry($this->config);
//         $registrys = $this->config['registry'];
//         if(count($registrys) > 0){
            
//         }
        $server = $this->getAvailableRegistryServer();
        $this->host = $server['host'];
        $this->port = $server['port'];
        $this->client = new SocketClient($this, $server['host'], $server['port']);
        $timer = new Timer(10000, array($this, "timer") );
        $timer->start();
    }
    private function initRegistry($config){
        $registrys = $config['registry'];
        if(count($registrys) > 0){
            foreach($registrys as $r){
                $registryServer = $r;
                $registryServer = parse_url($r);
                self::$regisrtyServer[] = array('host'=>$registryServer['host'], 'port'=>$registryServer['port']);
            }
        }
    }
    /**
     * 定时更新服务器状态到注册中心
     * @param unknown $id
     */
    public function timer($id){
        //echo "Timer={$id},".date("Y-m-d H:i:s")."\n";
        $address = $this->config['address'];
        $address = parse_url($address);
       
        $data = array(
            'type' => ThriftServerRegistry::THRIFT_SERVER,
            'host' => $address['host'],
            'port' => $address['port'],
            'time' => time(),
            'datetime' => date("Y-m-d H:i:s")
        );

        if ($this->client->isConnected() == false) {
            
            $server = $this->getAvailableRegistryServer();
            Log::info("retry to connect RegistryServer {$server['host']}:{$server['port']} ");
            $this->client->connect($server['host'], $server['port'], - 1);
        } else {
            $send_data = json_encode($data) . "\r\n";
            $this->client->send($send_data);
        }
        
    }
    
    
    public function connect(){
        $this->client->connect();
    }
    
    public function onConnect($cli){
        //Log::info("connect to registry server {$this->host}:{$this->port}");
    }
    public function onReceive($cli, $data){
        ThriftServerRegistry::$thriftServer = json_decode($data, true);
        Log::info("Receive registery servers info====".$data);
        if(count(ThriftServerRegistry::$thriftServer) > 0){
            $content = json_encode(ThriftServerRegistry::$thriftServer);
            FileUtil::saveThriftServer($content);
        }
    }
    
    public function onError($cli){
        Log::info("ThriftServerRegistry===onError");
    }
    public function onClose($cli){
        Log::info("RegistryServer===onClose");
    }

    private function getAvailableRegistryServer(){
        $count = count(self::$regisrtyServer);
        if($count > 1){
            $registryServer = self::$regisrtyServer[rand(0, $count - 1)];
        }
        else{
            $registryServer = self::$regisrtyServer[0];
        }
        return $registryServer;
    }
}

?>